"""
Grave! Important! Важно!

Proletoj el ĉiuj landoj, unuiĝu!
Workers of the world, unite!
Пролетарии всех стран, соединяйтесь!

https://tkom.pro
"""

from django.contrib import admin
from django import forms
from django.utils.translation import gettext_lazy as _
import json

from .models import *
from siriuso.forms.widgets import LingvoInputWidget, LingvoTextWidget
from universo_bazo.models import Realeco
from siriuso.utils.admin_mixins import TekstoMixin


# Форма категорий блоков
class KanvasoKategorioFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)
    realeco = forms.ModelMultipleChoiceField(
        label=_('Параллельные миры'),
        queryset=Realeco.objects.filter(forigo=False, publikigo=True)
    )

    class Meta:
        model = KanvasoKategorio
        fields = [field.name for field in KanvasoKategorio._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Категории блоков
@admin.register(KanvasoKategorio)
class KanvasoKategorioAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoKategorioFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = KanvasoKategorio


# Форма типов блоков
class KanvasoTipoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)
    realeco = forms.ModelMultipleChoiceField(
        label=_('Параллельные миры'),
        queryset=Realeco.objects.filter(forigo=False, publikigo=True)
    )

    class Meta:
        model = KanvasoTipo
        fields = [field.name for field in KanvasoTipo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Типы блоков
@admin.register(KanvasoTipo)
class KanvasoTipoAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoTipoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = KanvasoTipo


# Форма статусов блоков
class KanvasoStatusoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = KanvasoStatuso
        fields = [field.name for field in KanvasoStatuso._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Статусы блоков
@admin.register(KanvasoStatuso)
class KanvasoStatusoAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoStatusoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = KanvasoStatuso


# Владелец модели блока
class KanvasoPosedantoInline(admin.TabularInline):
    model = KanvasoPosedanto
    fk_name = 'kanvaso'
    extra = 1


# Форма блоков
class KanvasoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)
    kategorio = forms.ModelMultipleChoiceField(
        label=_('категория блоков'),
        queryset=KanvasoKategorio.objects.filter(forigo=False, publikigo=True)
    )
    sxablono_sistema_priskribo = forms.CharField(
        widget=LingvoTextWidget(), 
        label=_('Priskribo de sistema ŝablono'), 
        required=False
    )

    class Meta:
        model = Kanvaso
        fields = [field.name for field in Kanvaso._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_sxablono_sistema_priskribo(self):
        out = self.cleaned_data['sxablono_sistema_priskribo']
        try:
            out = json.loads(out)
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Блоки
@admin.register(Kanvaso)
class KanvasoAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoFormo
    list_display = ('id','krea_dato','statuso','forigo','nomo_teksto','sxablono_sistema_id','sxablono_sistema','sxablono_priskribo_teksto')
    exclude = ('id',)
    inlines = (KanvasoPosedantoInline,)
    list_filter = ('sxablono_sistema',)
    class Meta:
        model = Kanvaso


# Форма типов владельцев блоков
class KanvasoPosedantoTipoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = KanvasoPosedantoTipo
        fields = [field.name for field in KanvasoPosedantoTipo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Типы владельцев блоков
@admin.register(KanvasoPosedantoTipo)
class KanvasoPosedantoTipoAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoPosedantoTipoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = KanvasoPosedantoTipo


# Форма статусов владельцев блоков
class KanvasoPosedantoStatusoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = KanvasoPosedantoStatuso
        fields = [field.name for field in KanvasoPosedantoStatuso._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Статусы владельцев блоков
@admin.register(KanvasoPosedantoStatuso)
class KanvasoPosedantoStatusoAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoPosedantoStatusoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = KanvasoPosedantoStatuso


# Форма владельцев блоков
class KanvasoPosedantoFormo(forms.ModelForm):
    
    sxablono_sistema_priskribo = forms.CharField(
        widget=LingvoTextWidget(), 
        label=_('Priskribo de sistema ŝablono'), 
        required=False
    )

    class Meta:
        model = KanvasoPosedanto
        fields = [field.name for field in KanvasoPosedanto._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_sxablono_sistema_priskribo(self):
        out = self.cleaned_data['sxablono_sistema_priskribo']
        try:
            out = json.loads(out)
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Владельцы блоков
@admin.register(KanvasoPosedanto)
class KanvasoPosedantoAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoPosedantoFormo
    list_display = ('uuid','kanvaso','sxablono_sistema_id','sxablono_sistema','sxablono_priskribo_teksto')
    exclude = ('uuid',)
    list_filter = ('sxablono_sistema',)
    class Meta:
        model = KanvasoPosedanto


# Форма типов связей блоков между собой
class KanvasoLigiloTipoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Titolo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = KanvasoLigiloTipo
        fields = [field.name for field in KanvasoLigiloTipo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Типы связей блоков между собой
@admin.register(KanvasoLigiloTipo)
class KanvasoLigiloTipoAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoLigiloTipoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = KanvasoLigiloTipo


# Форма связей блоков между собой
class KanvasoLigiloFormo(forms.ModelForm):
    
    sxablono_sistema_priskribo = forms.CharField(
        widget=LingvoTextWidget(), 
        label=_('Priskribo de sistema ŝablono'), 
        required=False
    )

    class Meta:
        model = KanvasoLigilo
        fields = [field.name for field in KanvasoLigilo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_sxablono_sistema_priskribo(self):
        out = self.cleaned_data['sxablono_sistema_priskribo']
        try:
            out = json.loads(out)
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Связи блоков между собой
@admin.register(KanvasoLigilo)
class KanvasoLigiloAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoLigiloFormo
    list_display = ('posedanto','tipo','ligilo','sxablono_sistema_id','sxablono_sistema','sxablono_priskribo_teksto')
    exclude = ('uuid',)
    list_filter = ('sxablono_sistema',)
    class Meta:
        model = KanvasoLigilo


# Форма категорий карточек
class KanvasoObjektoKategorioFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)
    realeco = forms.ModelMultipleChoiceField(
        label=_('Параллельные миры'),
        queryset=Realeco.objects.filter(forigo=False, publikigo=True)
    )

    class Meta:
        model = KanvasoObjektoKategorio
        fields = [field.name for field in KanvasoObjektoKategorio._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Категорий карточек
@admin.register(KanvasoObjektoKategorio)
class KanvasoObjektoKategorioAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoObjektoKategorioFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = KanvasoObjektoKategorio


# Форма типов карточек
class KanvasoObjektoTipoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)
    realeco = forms.ModelMultipleChoiceField(
        label=_('Параллельные миры'),
        queryset=Realeco.objects.filter(forigo=False, publikigo=True)
    )

    class Meta:
        model = KanvasoObjektoTipo
        fields = [field.name for field in KanvasoObjektoTipo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Типы карточек
@admin.register(KanvasoObjektoTipo)
class KanvasoObjektoTipoAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoObjektoTipoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = KanvasoObjektoTipo


# Форма статусов карточек
class KanvasoObjektoStatusoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = KanvasoObjektoStatuso
        fields = [field.name for field in KanvasoObjektoStatuso._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Статус карточек
@admin.register(KanvasoObjektoStatuso)
class KanvasoObjektoStatusoAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoObjektoStatusoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = KanvasoObjektoStatuso


# Форма карточек
class KanvasoObjektoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)
    kategorio = forms.ModelMultipleChoiceField(
        label=_('Kategorio de kanvaso objektoj'),
        queryset=KanvasoObjektoKategorio.objects.filter(forigo=False, publikigo=True)
    )
    sxablono_sistema_priskribo = forms.CharField(
        widget=LingvoTextWidget(), 
        label=_('Priskribo de sistema ŝablono'), 
        required=False
    )

    class Meta:
        model = KanvasoObjekto
        fields = [field.name for field in KanvasoObjekto._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_sxablono_sistema_priskribo(self):
        out = self.cleaned_data['sxablono_sistema_priskribo']
        try:
            out = json.loads(out)
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Владелец карточек
class KanvasoObjektoPosedantoInline(admin.TabularInline):
    model = KanvasoObjektoPosedanto
    fk_name = 'kanvaso_objekto'
    extra = 1


# Карточки
@admin.register(KanvasoObjekto)
class KanvasoObjektoAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoObjektoFormo
    list_display = ('uuid', 'id','krea_dato','tipo','nomo_teksto','kanvaso','priskribo_teksto','forigo','sxablono_sistema_id','sxablono_sistema','sxablono_priskribo_teksto')
    exclude = ('uuid',)
    inlines = (KanvasoObjektoPosedantoInline,)
    list_filter = ('sxablono_sistema','kanvaso__id')
    class Meta:
        model = KanvasoObjekto


# Форма типов владельцев карточек
class KanvasoObjektoPosedantoTipoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = KanvasoObjektoPosedantoTipo
        fields = [field.name for field in KanvasoObjektoPosedantoTipo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Типы владельцев карточек
@admin.register(KanvasoObjektoPosedantoTipo)
class KanvasoObjektoPosedantoTipoAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoObjektoPosedantoTipoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = KanvasoObjektoPosedantoTipo


# Форма статусов владельцев карточек
class KanvasoObjektoPosedantoStatusoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Nomo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = KanvasoObjektoPosedantoStatuso
        fields = [field.name for field in KanvasoObjektoPosedantoStatuso._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Статусы владельцев карточек
@admin.register(KanvasoObjektoPosedantoStatuso)
class KanvasoObjektoPosedantoStatusoAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoObjektoPosedantoStatusoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = KanvasoObjektoPosedantoStatuso


# Форма владельцев карточек
class KanvasoObjektoPosedantoFormo(forms.ModelForm):

    sxablono_sistema_priskribo = forms.CharField(
        widget=LingvoTextWidget(), 
        label=_('Priskribo de sistema ŝablono'), 
        required=False
    )

    class Meta:
        model = KanvasoObjektoPosedanto
        fields = [field.name for field in KanvasoObjektoPosedanto._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_sxablono_sistema_priskribo(self):
        out = self.cleaned_data['sxablono_sistema_priskribo']
        try:
            out = json.loads(out)
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Владельцы карточек
@admin.register(KanvasoObjektoPosedanto)
class KanvasoObjektoPosedantoAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoObjektoPosedantoFormo
    list_display = ('uuid','kanvaso_objekto','sxablono_sistema_id','sxablono_sistema','sxablono_priskribo_teksto')
    exclude = ('uuid',)
    list_filter = ('sxablono_sistema',)
    class Meta:
        model = KanvasoObjektoPosedanto


# Форма типов связей карточек между собой
class KanvasoObjektoLigiloTipoFormo(forms.ModelForm):
    
    nomo = forms.CharField(widget=LingvoInputWidget(), label=_('Titolo'), required=False)
    priskribo = forms.CharField(widget=LingvoInputWidget(), label=_('Priskribo'), required=False)

    class Meta:
        model = KanvasoObjektoLigiloTipo
        fields = [field.name for field in KanvasoObjektoLigiloTipo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_nomo(self):
        out = self.cleaned_data['nomo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out

    def clean_priskribo(self):
        out = self.cleaned_data['priskribo']
        try:
            out = json.loads(out)
            chefa_idx = out['lingvo'][out['chefa_varianto']] if out['chefa_varianto'] in out['lingvo'] else -1
            if not len(out['enhavo']) or (chefa_idx != -1 and not out['enhavo'][chefa_idx]):
                raise forms.ValidationError(_('This field is required.'))
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Типы связей карточек между собой
@admin.register(KanvasoObjektoLigiloTipo)
class KanvasoObjektoLigiloTipoAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoObjektoLigiloTipoFormo
    list_display = ('id','nomo_teksto','autoro_nn','autoro_email')
    exclude = ('uuid',)
    autocomplete_fields = ['autoro']

    class Meta:
        model = KanvasoObjektoLigiloTipo


# Форма связей карточек между собой
class KanvasoObjektoLigiloFormo(forms.ModelForm):
    
    sxablono_sistema_priskribo = forms.CharField(
        widget=LingvoTextWidget(), 
        label=_('Priskribo de sistema ŝablono'), 
        required=False
    )

    class Meta:
        model = KanvasoObjektoLigilo
        fields = [field.name for field in KanvasoObjektoLigilo._meta.fields if field.name not in ('krea_dato', 'uuid')]

    def clean_sxablono_sistema_priskribo(self):
        out = self.cleaned_data['sxablono_sistema_priskribo']
        try:
            out = json.loads(out)
        except json.JSONDecodeError:
            raise forms.ValidationError(_('Недопустимые данные в JSON поле'))
        return out


# Связи карточек между собой
@admin.register(KanvasoObjektoLigilo)
class KanvasoObjektoLigiloAdmin(admin.ModelAdmin, TekstoMixin):
    form = KanvasoObjektoLigiloFormo
    list_display = ('uuid','posedanto','tipo','ligilo','forigo','sxablono_sistema_id','sxablono_sistema','sxablono_priskribo_teksto')
    exclude = ('uuid',)
    list_filter = ('sxablono_sistema',)
    class Meta:
        model = KanvasoObjektoLigilo
